package com.ruoyi.school.event;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.openapi.event.EventService;
import org.openapi.service.IDbService;
import org.openapi.vo.TableQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 新增学生信息前，自动创建账号
 */
@Component
public class InsertStudentEvent implements EventService {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IDbService dbService;
    @Override
    public void process(Object data) {
        Map<String,Object> studentData = (Map<String,Object>)data;

        Long roles[] = {5L};
        SysUser user = new SysUser();
        user.setDeptId(0L);
        user.setDelFlag("0");
        if(studentData.get("email") != null){
            user.setEmail(studentData.get("email").toString());
        }
        user.setNickName(studentData.get("name").toString());
        user.setPhonenumber(studentData.get("phone").toString());
        user.setRoleIds(roles);
        user.setSex(studentData.get("sex").toString());
        user.setStatus("0");
        user.setUserName(studentData.get("phone").toString());

        String password = configService.selectConfigByKey("sys.user.initPassword");
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateTime(new Date());
        userService.insertUser(user);

        studentData.put("user_id", user.getUserId());
    }
}
